package com.pentajock.docdb.dialogs;

import com.pentajock.docdb.AdminWindow;
import com.pentajock.docdb.Main;
import com.pentajock.docdb.database.DBController;
import com.pentajock.docdb.images.DBImages;
import com.pentajock.docdb.lang.Lang;
import com.pentajock.docdb.types.DepartmentProperties;
import com.pentajock.docdb.utils.Utils;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;

public class DepartmentPropertiesDialog extends JDialog {

	private JList departmentPropertiesList;
	private JButton deletePropertyButton;
	private JButton createNewPropertyButton;
	private JButton acceptChangesButton;
	private JButton revertChangesButton;
	
	private JCheckBox showInHeaderButton;
	private JTextField positionInHeaderField;
	private JCheckBox showInPropertiesButton;
	private JCheckBox isStaticButton;
	private JTextField staticValueField;
	
	private JButton okButton;
	private AdminWindow window;
	
	private DefaultListModel departmentPropertiesListModel;
	private String departmentName;
	//private DepartmentPropertiesDialog properties;
        private DepartmentProperties properties;
	private final String COLON = Lang.MISC.getText("CHOICE_DELIMITER", ":");
	private final String NOT_AVAIL = Lang.MISC.getText("NOT_AVAILABLE", "<n/a>");
	
	public DepartmentPropertiesDialog(String departmentName, AdminWindow window) throws SQLException {
		super(window, Lang.DIALOG.getText("EDIT_DEPARTMENT_PROPERTIES", "Edit Department Properties"), true);
		Utils.setIconImage(this, DBImages.GROUP_ICON.getImage());
		this.window = window;
		if (departmentName.equalsIgnoreCase(Lang.MISC.getText("LOST_AND_FOUND", "Lost & Found")))
			this.departmentName = "-1";
		this.departmentName = departmentName;
		
		initializeObjects();
		layoutFrame();
		addListeners();
		
		departmentPropertiesList.setSelectedIndex(0);
		updatePropertyFields(true);
		
		getRootPane().setDefaultButton(okButton);
		setResizable(false);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		pack();
		setLocationRelativeTo(window);
	}
	
	private void loadPropertiesFromDatabase() throws SQLException {
		properties = DBController.getDepartmentPropertiesFull(departmentName);
	}
	
	private void populatePropertyListModel() throws SQLException {
		loadPropertiesFromDatabase();
		departmentPropertiesListModel.clear();
		for(String propertyName : properties.getPropertyNames()) {
			departmentPropertiesListModel.addElement(propertyName);
		}
	}
	
	private void updatePropertyFields(boolean initialize) {
		Object o = departmentPropertiesList.getSelectedValue();
		if (o==null) return;
		String propertyName = (String)o;
		DepartmentProperties.Property prop = properties.getProperty(propertyName);
		
		if(initialize) {
			if((Boolean)prop.get(DepartmentProperties.PropertyID.LOCKED)) {
				deletePropertyButton.setEnabled(false);
			}
			else {
				deletePropertyButton.setEnabled(true);
			}
			showInHeaderButton.setSelected((Boolean)prop.get(DepartmentProperties.PropertyID.SHOW_IN_HEADER));
			showInPropertiesButton.setSelected((Boolean)prop.get(DepartmentProperties.PropertyID.SHOW_IN_PROPERTIES));
			isStaticButton.setSelected((Boolean)prop.get(DepartmentProperties.PropertyID.IS_STATIC));
		}
		
		if(showInHeaderButton.isSelected()) {
			positionInHeaderField.setEnabled(true);
			positionInHeaderField.setText(((Integer)prop.get(DepartmentProperties.PropertyID.POSITION_IN_HEADER)).toString());
		}
		else {
			positionInHeaderField.setEnabled(false);
			positionInHeaderField.setText(NOT_AVAIL);
		}
		
		if(isStaticButton.isSelected()) {
			staticValueField.setEnabled(true);
			staticValueField.setText((String)prop.get(DepartmentProperties.PropertyID.STATIC_VALUE));
		}
		else {
			staticValueField.setEnabled(false);
			staticValueField.setText(NOT_AVAIL);
		}
	}
	
	private void initializeObjects() throws SQLException {
		departmentPropertiesListModel = new DefaultListModel();
		populatePropertyListModel();
		departmentPropertiesList = new JList(departmentPropertiesListModel);
		departmentPropertiesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		//deletePropertyButton = new JButton("Add Property");
		//createNewPropertyButton = new JButton("Remove Property");
		//okButton = new JButton("Close Dialog");
		//acceptChangesButton = new JButton("Accept");
		//revertChangesButton = new JButton("Revert");
		
		deletePropertyButton = new JButton(DBImages.REMOVE_BUTTON.getIcon());
		deletePropertyButton.setEnabled(false);
		createNewPropertyButton = new JButton(DBImages.ADD_BUTTON.getIcon());
	
		showInHeaderButton = new JCheckBox(Lang.DIALOG.getText("DOCUMENT_HEADER_SHOW", "Show in Document Header"), false);
		positionInHeaderField = new JTextField(5);
		showInPropertiesButton = new JCheckBox(Lang.DIALOG.getText("DOCUMENT_PROPERTIES_SHOW", "Show in Document Properties"), true);
		isStaticButton = new JCheckBox(Lang.DIALOG.getText("STATIC_VALUE", "Static Value"));
		isStaticButton.setEnabled(false);
		staticValueField = new JTextField(16);
		
		okButton = new JButton(Lang.BUTTON.getText("CLOSE", "Close"));
		okButton.setMnemonic(Lang.BUTTON.getMnemonic("CLOSE", KeyEvent.VK_C));
		acceptChangesButton = new JButton(Lang.BUTTON.getText("SAVE", "Save"), DBImages.SAVE_BUTTON.getIcon());
		acceptChangesButton.setMnemonic(Lang.BUTTON.getMnemonic("SAVE", KeyEvent.VK_S));
		revertChangesButton = new JButton(Lang.BUTTON.getText("REVERT", "Revert"), DBImages.REVERT_BUTTON.getIcon());
		revertChangesButton.setMnemonic(Lang.BUTTON.getMnemonic("REVERT", KeyEvent.VK_R));
	}
	
	private void layoutFrame() {
		//
		JScrollPane departmentPropertiesScroll = new JScrollPane(departmentPropertiesList);
		departmentPropertiesScroll.setPreferredSize(new Dimension(100, 200));
		
		JPanel listButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		listButtonPanel.add(createNewPropertyButton);
		listButtonPanel.add(deletePropertyButton);
		
		Box departmentPropertiesContainer = new Box(BoxLayout.Y_AXIS);
		departmentPropertiesContainer.add(departmentPropertiesScroll);
		departmentPropertiesContainer.add(listButtonPanel);
		
		createNewPropertyButton.setBorder(BorderFactory.createEtchedBorder());
		deletePropertyButton.setBorder(BorderFactory.createEtchedBorder());
		acceptChangesButton.setBorder(BorderFactory.createEtchedBorder());
		revertChangesButton.setBorder(BorderFactory.createEtchedBorder());
		
		//departmentPropertiesContainer.add(createNewPropertyButton);
		//departmentPropertiesContainer.add(deletePropertyButton);
		//
		JPanel positionInHeaderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		positionInHeaderPanel.add(new JLabel(Lang.DIALOG.getText("HEADER_POSITION", "Position in Header") + COLON));
		positionInHeaderPanel.add(positionInHeaderField);
		
		JPanel staticValuePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		staticValuePanel.add(new JLabel(Lang.DIALOG.getText("STATIC_VALUE", "Static Value") + COLON));
		staticValuePanel.add(staticValueField);
		
		JPanel updaterButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		updaterButtonPanel.add(acceptChangesButton);
		updaterButtonPanel.add(revertChangesButton);
		
		JPanel propertyDetailsContainer = new JPanel(new GridLayout(6, 1));
		propertyDetailsContainer.add(showInHeaderButton);
		propertyDetailsContainer.add(positionInHeaderPanel);
		propertyDetailsContainer.add(showInPropertiesButton);
		propertyDetailsContainer.add(isStaticButton);
		propertyDetailsContainer.add(staticValuePanel);
		propertyDetailsContainer.add(updaterButtonPanel);
		propertyDetailsContainer.setBorder(BorderFactory.createTitledBorder(Lang.DIALOG.getText("PROPERTY DETAILS", "Property Details")));
		//
		JPanel centerContainer = new JPanel(new FlowLayout());
		centerContainer.add(departmentPropertiesContainer);
		centerContainer.add(propertyDetailsContainer);
		//
		JPanel closeButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		closeButtonPanel.add(okButton);
		
		getContentPane().add(centerContainer, BorderLayout.CENTER);
		getContentPane().add(closeButtonPanel, BorderLayout.SOUTH);
	}
	
	private void addListeners() {
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		
		createNewPropertyButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String propertyName = JOptionPane.showInputDialog(DepartmentPropertiesDialog.this, "Enter the name of your property", "Create New Property", JOptionPane.QUESTION_MESSAGE);
				try {
					boolean success = DBController.addDepartmentProperty(departmentName, propertyName);
					if(success) {
						JOptionPane.showMessageDialog(DepartmentPropertiesDialog.this, "Property Created.", "Success!", JOptionPane.INFORMATION_MESSAGE);
						populatePropertyListModel();
						departmentPropertiesList.setSelectedValue(propertyName, true);
					}
					else {
						JOptionPane.showMessageDialog(DepartmentPropertiesDialog.this, "An error occured.", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
				catch(SQLException ex) {
					Main.printStackTrace(ex, "Error adding new department property");
				}
				catch (Exception ex) {
					Main.printStackTrace(ex, "Unknown exception");
				}
			}
		});
		
		deletePropertyButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					boolean success = DBController.deleteDepartmentProperty(departmentName, (String)departmentPropertiesList.getSelectedValue());
					populatePropertyListModel();
					if(success) {
						departmentPropertiesList.setSelectedIndex(0);
					}
				}
				catch(SQLException ex) {
					Main.printStackTrace(ex, "error deleting Department Property");
				}
				catch (Exception ex) {
					Main.printStackTrace(ex, "Unknown exception");
				}
			}
		});
		
		showInHeaderButton.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				updatePropertyFields(false);
			}
		});
		
		isStaticButton.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				updatePropertyFields(false);
			}
		});
		
		departmentPropertiesList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				updatePropertyFields(true);
			}
		});
	}
}
